import { animate, AnimationEvent, style, transition, trigger } from '@angular/animations';
import { Component, OnInit, ChangeDetectionStrategy, Input, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { Subscription, timer } from 'rxjs';
import { MessageComponent } from '../message.component';
import { XmMessageItemData } from '../types';

@Component({
  selector: 'app-message-item',
  templateUrl: './message-item.component.html',
  styleUrls: ['./message-item.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('moveUpMotion', [
      transition('*=>enter', [
        style({
          opacity: 0,
          transform: 'translateY(-100%)',
        }),
        animate(
          '.2s',
          style({
            opacity: 1,
            transform: 'translateY(0)',
          })
        ),
      ]),
      transition('*=>leave', [
        animate(
          '.2s',
          style({
            opacity: 0,
            transform: 'translateY(-100%)',
          })
        ),
      ]),
    ]),
  ],
})
export class MessageItemComponent implements OnInit, OnDestroy {
  @Input() index = 0;
  @Input() message: XmMessageItemData;
  private autoClose = true;
  private timerSub: Subscription;
  get itemCls(): string {
    return 'xm-message clearfix ' + this.message.options.type;
  }
  constructor(
    private parent: MessageComponent,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    const { duration } = this.message.options;
    this.autoClose = this.message.options.duration > 0;
    if (this.autoClose) {
      this.createTimer(duration);
    }
  }
  private createTimer(duration: number): void {
    this.timerSub = timer(duration).subscribe(() => {
      this.close();
    });
  }
  private clearTimer() {
    if (this.timerSub) {
      this.timerSub.unsubscribe();
      this.timerSub = null;
    }
  }
  animationDone(event:AnimationEvent):void {
    if (event.toState === 'leave') {
      this.parent.removeMessage(this.message.messageId);
    }
  }
  close(): void {
    this.message.state = 'leave';
    this.cdr.markForCheck();
    
  }
  enter(): void {
    if (this.autoClose && this.message.options.pauseOnHover) {
      this.clearTimer();
    }
  }
  leave(): void {
    if (this.autoClose && this.message.options.pauseOnHover) {
      this.createTimer(this.message.options.duration);
    }
  }
  ngOnDestroy(): void {
    this.clearTimer();
  }
}
